package mapper.session;

import mapper.datasource.DataSourceContextHolder;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.HashMap;

public class MapperApiSqlSessionFactory {

    public static SqlSessionFactory buildSqlSessionFactory(String dsName) {
        DataSource dataSource = DataSourceContextHolder.get(dsName);
        Environment environment = new Environment(dsName, new JdbcTransactionFactory(), dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(HashMap.class);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(configuration);
        return factory;

    }

    public String getSelectSqlByName(String name) {
        return new SQL() {
            {
                SELECT("*");
                FROM("testtt");
                WHERE("field1 like #{field1} || '%'");
            }
        }.toString();
    }
}